package com.qujia.station.controller;

import com.qujia.common.annotation.Log;
import com.qujia.common.constant.UserConstants;
import com.qujia.common.core.controller.BaseController;
import com.qujia.common.core.domain.AjaxResult;
import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.core.redis.RedisCache;
import com.qujia.common.enums.BusinessType;
import com.qujia.common.enums.ErrorCode;
import com.qujia.common.exception.CustomException;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.common.utils.StringUtils;
import com.qujia.station.domain.Station;
import com.qujia.station.domain.img;
import com.qujia.station.domain.vo.StaffVO;
import com.qujia.station.domain.vo.StationResVo;
import com.qujia.station.service.*;
import com.qujia.system.service.ISysUserService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("/syncStation")
@Api(tags = "油站信息Controller", description = "油站信息同步")
@Slf4j
public class StationSyncController extends BaseController {
    @Autowired
    private IStationService stationService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IStaffService staffService;

    @Log(title = "增加油站", businessType = BusinessType.INSERT)
    @PostMapping("/addStation/{timestamp}/{sign}")
    public AjaxResult add(@RequestBody Station station)
    {
        log.info("同步 新增油站======");
        int m=0;
        Calendar cal = Calendar.getInstance();
        String regionData1="";
        String licenseImg="";
        String ImgName="";
        if (station.getRegionDataList() !=null&&station.getRegionDataList().length>0) {
            for (String regionData : station.getRegionDataList()) {
                if ("".equals(regionData1)) {
                    regionData1 += regionData;
                } else {
                    regionData1 += "," + regionData;
                }
            }

            if (!"".equals(regionData1)) {
                station.setRegionData(regionData1);
            }
        }
        if (station.getImgFileList()!=null&&station.getImgFileList().size()>0) {
            for (img img1 : station.getImgFileList()) {
                if ("".equals(licenseImg)) {
                    licenseImg += img1.getUrl();
                    ImgName +=img1.getName();
                } else {
                    licenseImg +="," +img1.getUrl();
                    ImgName +=","+img1.getName();
                }
            }

            if (!"".equals(licenseImg)) {
                station.setImgUrl(licenseImg);
                station.setImgName(ImgName);
            }
        }
        Random random=new Random();
        String result1 = "";
        for (int i = 0; i < 4; i++) {
            result1 += random.nextInt(10);
        }
        int year = cal .get(Calendar.YEAR);
        int month = cal .get(Calendar.MONTH) + 1;
        int yearcount=year-2000;
        String code="S"+yearcount+month+"0001"+result1;
        station.setStationCode(code);
        station.setImgName("123.jpg");
        m=stationService.insertStation(station);

        if(m<=0){
            return  toAjax(0);

        }
        Long[] roles={Long.parseLong(19+"")};
        //Station station1=stationService.selectStationList(station).get(0);
        SysUser sysUser=new SysUser();
        sysUser.setDeptId((long) 100);
        sysUser.setUserName(code);
        sysUser.setNickName(station.getStationName());
        sysUser.setUserLevel("2");
        sysUser.setPhonenumber(station.getPhone());
        sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
        sysUser.setStationId(station.getStationId());
        sysUser.setRoleIds(roles);
        sysUser.setEnterpriseId(station.getEnterpriseId());
        sysUserService.insertUser(sysUser);
        return AjaxResult.success(station.getStationId());
    }


    @Log(title = "油站信息", businessType = BusinessType.UPDATE)
    @PostMapping("/updateStation/{timestamp}/{sign}")
    public AjaxResult edit(@RequestBody Station station)
    {
        System.out.println("修改--------------");


        if ( StringUtils.equals("1",station.getNeedStaff())) {
            StaffVO staffVO = new StaffVO();
            staffVO.setStationId(station.getStationId());
            staffVO.setUserLevel(UserConstants.LEVEL_THREE);
        }

        String regionData1="";
        String licenseImg="";
        String ImgName="";
        if (station.getRegionDataList() !=null&&station.getRegionDataList().length>0) {
            for (String regionData : station.getRegionDataList()) {
                if ("".equals(regionData1)) {
                    regionData1 += regionData;
                } else {
                    regionData1 += "," + regionData;
                }
            }

            if (!"".equals(regionData1)) {
                station.setRegionData(regionData1);
            }
        }
        if (station.getImgFileList()!=null&&station.getImgFileList().size()>0) {
            for (img img1 : station.getImgFileList()) {
                if ("".equals(licenseImg)) {
                    licenseImg += img1.getUrl();
                    ImgName +=img1.getName();
                } else {
                    licenseImg +="," +img1.getUrl();
                    ImgName +=","+img1.getName();
                }
            }

            if (!"".equals(licenseImg)) {
                station.setImgUrl(licenseImg);
                station.setImgName(ImgName);
            }
        }
        SysUser sysUser=new SysUser();
        sysUser.setStationId(station.getStationId());
        List<SysUser> sysUserList= sysUserService.selectUserList(sysUser);
        if(sysUserList!=null && sysUserList.size()>0){
            for(SysUser sysUser1:sysUserList){
                sysUser1.setEnterpriseId(station.getEnterpriseId());
                sysUserService.updateUserProfile(sysUser);
            }
        }
        redisCache.deleteObject("EnterpriseServiceImpl_selectStaInfoList::" + "e_" +station.getEnterpriseId() );
        redisCache.deleteObject("EnterpriseServiceImpl_selectStaOilGunList::" + "s_" +station.getStationId() );
        redisCache.deleteObject("EnterpriseServiceImpl_selectStationById::" + "s_" +station.getStationId() );
        redisCache.deleteObject("EnterpriseServiceImpl_selectEnterpriseInfo::" + "e_" +station.getEnterpriseId() );
        return toAjax(stationService.updateStation(station));
    }

    /**
     * 获取油站信息详细信息
     */
    @GetMapping(value = "/{stationId}/{timestamp}/{sign}")
    public AjaxResult getInfo(@PathVariable("stationId") Long stationId)
    {
        Station station=stationService.selectStationById(stationId);
        if(station.getRegionData()!=null) {
            station.setRegionDataList(station.getRegionData().split(","));
        }
        List<img>  imgs=new ArrayList<>();
        if(station.getImgUrl()!=null){
            String[] message= station.getImgUrl().split(",");
            String[] name= station.getImgName().split(",");

            for(int i=0;i<name.length;i++){
                img img2=new img();
                img2.setName(name[i]);
                img2.setUrl(message[i]);
                imgs.add(img2);
            }
        }
        station.setImgFileList(imgs);
        return AjaxResult.success(station);
    }


}
